package org.lhl.readruler

import android.Manifest
import android.app.AlertDialog
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.PermissionUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.item_recyclerview_storage.view.*
import kotlinx.android.synthetic.main.toolbar.*
import lhl.kotlinextends.*
import org.lhl.readruler.bean.DataValue
import org.lhl.readruler.bean.DeviceStorage
import org.lhl.readruler.connection.Event
import org.lhl.readruler.manager.*
import org.lhl.readruler.utils.DataTool
import org.lhl.readruler.widget.RecyclerAdapter
import kotlin.system.exitProcess

class MainActivity : BaseActivity() {
    private var firstPressedTime = 0L
    private val isSupportBLE by lazy { BluetoothAdapter.getDefaultAdapter() != null }
    private val storages = mutableListOf<DeviceStorage>()
    private val recyData = mutableListOf<DataValue>()
    private val data0 = mutableListOf<DataValue>()
    private val data1 = mutableListOf<DataValue>()
    private val data2 = mutableListOf<DataValue>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tvTitle.text = "数据读取"
        imgBack.visibility = View.GONE
        btnBluetooth.visible = true
        btnBluetooth.click {
            if (isNotSupportBLE()) return@click
            startActivity(Intent(this, DeviceActivity::class.java))
        }

        btnRead.click {
            if (isNotSupportBLE()) return@click
            if (!DeviceManager.isConnected()) {
                "请先连接设备".toast()
                return@click
            }
            storages.clear()
            data0.clear()
            data1.clear()
            data2.clear()
            recyData.clear()
            rcyStorage.adapter?.notifyDataSetChanged()
            DeviceManager.getDeviceStorage()
        }

//        btnClear.click {
//            storages.clear()
//            data0.clear()
//            data1.clear()
//            data2.clear()
//            recyData.clear()
//            rcyStorage.adapter?.notifyDataSetChanged()
//        }

        btnExport.click {
            if (storages.isEmpty()) {
                "没有数据可导出".toast()
                return@click
            }
            val wait = PDialog("正在导出..").show()
            ExcelManager.export(storages).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
                wait.dismiss()
                "导出完成".toast()
                TDialog("导出完成：$it").show()
            }) {
                wait.dismiss()
                TDialog("导出出错：$it").show()
            }.auto("export")
        }

        DeviceManager.registerChangeListener().observeOn(AndroidSchedulers.mainThread()).subscribe({
            when (it.attribute) {
                Event.DATA_META -> {
                    "接收数据：${DataTool.bytesToHexString(it.value as ByteArray)}".e()
                }
                Event.DEVICE_STORAGE -> {
                    val storage = it.value as DeviceStorage
                    storage.e()
                    if (storage.totalAmount == 0) {
                        "没有存储数据".toast()
                        return@subscribe
                    }

                    storages.firstOrNull { it.stepIndex == storage.stepIndex }?.let {
                        val lastPointIndex = it.data.last().pointIndex
                        val lastMileage = it.data.last().mileage + if (it.data.last().abTrack == "左股") it.interval else (-1 * it.interval)
                        storage.data.forEach {
                            it.pointIndex += lastPointIndex
                            it.mileage = (it.mileage - storage.startMileage) + lastMileage
                        }
                    }

                    storages.add(storage)


                    val d1 = storage.data.filter { it.type and 0xc0 == TYPE_GUIJU_CHAOGAO }
                    val d2 = storage.data.filter { it.type and 0xc0 == TYPE_CHAZHAO_HUBEI }
                    val d3 = storage.data.filter { it.type and 0xc0 == TYPE_MAX_MIN }
                    data0.addAll(d1)
                    data1.addAll(d2)
                    data2.addAll(d3)
                    when (rgGroup.checkedRadioButtonId) {
                        R.id.rbGuiJu -> recyData.addAll(d1)
                        R.id.rbChaZHao -> recyData.addAll(d2)
                        R.id.rbMaxMin -> recyData.addAll(d3)
                    }
                    rcyStorage.adapter?.notifyDataSetChanged()
                }
            }
        }) {
            it.printStackTrace()
        }.auto()


        rgGroup.setOnCheckedChangeListener { radioGroup, i ->
            recyData.clear()
            when (i) {
                R.id.rbGuiJu -> {
                    tvHeadParam1.text = "轨距"
                    tvHeadParam2.text = "超高"
                    recyData.addAll(data0)
                }
                R.id.rbChaZHao -> {
                    tvHeadParam1.text = "查照"
                    tvHeadParam2.text = "护背"
                    recyData.addAll(data1)
                }
                R.id.rbMaxMin -> {
                    tvHeadParam1.text = "最大轨距"
                    tvHeadParam2.text = "最小轨距"
                    recyData.addAll(data2)
                }
            }
            rcyStorage.adapter?.notifyDataSetChanged()
        }

        rcyStorage.adapter = RecyclerAdapter(recyData, R.layout.item_recyclerview_storage) {
            tvStepIndex.text = it.stepIndex.toString()
            tvPointIndex.text = it.pointIndex.toString()
            tvMileage.text = it.mileage.kps(3)
            tvAbtrack.text = it.abTrack
            tvParam1.text = it.d1.kps(2)
            tvParam2.text = it.d2.kps(2)
        }


        PermissionUtils.permission(*arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION)).callback(object : PermissionUtils.FullCallback {
            override fun onGranted(permissionsGranted: MutableList<String>) {
            }

            override fun onDenied(permissionsDeniedForever: MutableList<String>, it: MutableList<String>) {
                "大小${it.size}".e()
                it.forEach { "权限:${it}\n".e() }
                val builder = AlertDialog.Builder(this@MainActivity)
                builder.setTitle("提示")
                builder.setMessage("缺少APP运行必要权限！")
                builder.setNegativeButton("退出") { _, _ ->
                    finish()
                }
                builder.setPositiveButton("前往设置") { _, _ ->
                    PermissionUtils.launchAppDetailsSettings()
                    finish()
                }
                builder.create().run {
                    setCancelable(false)
                    setCanceledOnTouchOutside(false)
                    show()
                }
            }
        }).request()

    }


    private fun isNotSupportBLE(): Boolean {
        if (!isSupportBLE)
            "设备不支持BLE蓝牙".toastLong()
        return !isSupportBLE
    }


    override fun onBackPressed() {
        "再按一次退出".toast()
        if (System.currentTimeMillis() - firstPressedTime < 2000) {
            super.onBackPressed()
            exitProcess(0)
        } else {
            firstPressedTime = System.currentTimeMillis()
        }
    }
}